package d;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import d.ConnectionManager;



public class SQLScript {
	public static final String COMMAND_DELIMITER = ";";

	private File scriptFile;
	
	public SQLScript(String fullPath) {
		scriptFile = new File(fullPath);
		if(!(scriptFile.exists()&&scriptFile.isFile())) 
		{
			throw new RuntimeException(String.format("Invalid SQL script file \"%s\"!",fullPath));
		}
	}
	
	public void execute() throws SQLException {
		Connection conn = ConnectionManager.getConnection();
		conn.setAutoCommit(false);

		try {
			BufferedReader br = new BufferedReader(new FileReader(scriptFile));
			String line;
			StringBuffer lineBuffer = new StringBuffer();
			while((line = br.readLine())!=null) {
				line = line.trim();
				
				if(line.length()==0) {
					continue;
				}

				lineBuffer.append(" ");
				lineBuffer.append(line);
				if(line.endsWith(COMMAND_DELIMITER)){
					conn.createStatement().execute(lineBuffer.toString());
					lineBuffer.setLength(0);
				}
			}
			conn.commit();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		ConnectionManager.freeConnection(conn);
	}
}
